package com.yyaccp.hncc.dms.controller;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.yyaccp.hncc.common.DmsConstants;
import com.yyaccp.hncc.common.util.BeanCopierUtil;
import com.yyaccp.hncc.common.vo.dms.DmsMedicinePrescriptionRecordVO;
import com.yyaccp.hncc.dms.domain.DmsMedicineItemRecord;
import com.yyaccp.hncc.dms.domain.DmsMedicinePrescriptionRecord;
import com.yyaccp.hncc.dms.service.IDmsMedicinePrescriptionRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 成药处方Controller
 *
 * @author ruoyi
 * @date 2020-08-26
 */
@Api(tags = "成药处方")
@RestController
@RequestMapping("/dms/medicine_prescription_record")
public class DmsMedicinePrescriptionRecordController extends BaseController {
    @Autowired
    private IDmsMedicinePrescriptionRecordService dmsMedicinePrescriptionRecordService;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private RedisTemplate<String, DmsMedicinePrescriptionRecord> redisTemplate;

    /**
     * 查询成药处方列表
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询成药处方", notes = "查询所有成药处方",
            code = 200, produces = "application/json", protocols = "Http",
            response = TableDataInfo.class, httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsMedicinePrescriptionRecordVO对象", type = "DmsMedicinePrescriptionRecordVO")
    public TableDataInfo list(DmsMedicinePrescriptionRecordVO dmsMedicinePrescriptionRecordVO) {
        //将Vo转化为实体
        DmsMedicinePrescriptionRecord dmsMedicinePrescriptionRecord = BeanCopierUtil.copy(dmsMedicinePrescriptionRecordVO, DmsMedicinePrescriptionRecord.class);
        //获取缓存中的数据
        String key = DmsConstants.PRESCRIPTION_FOLDER + ":" + dmsMedicinePrescriptionRecord.getRegistrationId() + ":" + DmsConstants.CORRESPONDING_REGISTRATION;
        List<DmsMedicinePrescriptionRecord> records = redisCache.getCacheList(key);
        //设置分页
        startPage();
        List<DmsMedicinePrescriptionRecord> list = dmsMedicinePrescriptionRecordService.selectDmsMedicinePrescriptionRecordList(dmsMedicinePrescriptionRecord);
        //将缓存数据加入分页数据
        list.addAll(records);
        TableDataInfo tableDataInfo = getDataTable(list);
        //替换集合
        tableDataInfo.setRows(BeanCopierUtil.copy(tableDataInfo.getRows(), DmsMedicinePrescriptionRecordVO.class));
        return tableDataInfo;
    }

    /**
     * 导出成药处方列表
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:export')")
    @Log(title = "成药处方", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value = "导出成药处方表", notes = "导出所有成药处方",
            code = 200, produces = "application/json", protocols = "Http",
            response = TableDataInfo.class, httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsMedicinePrescriptionRecordVO对象", type = "DmsMedicinePrescriptionRecordVO")
    public AjaxResult export(DmsMedicinePrescriptionRecordVO dmsMedicinePrescriptionRecordVO) {
        //将VO转化为实体
        DmsMedicinePrescriptionRecord dmsMedicinePrescriptionRecord = BeanCopierUtil.copy(dmsMedicinePrescriptionRecordVO, DmsMedicinePrescriptionRecord.class);
        List<DmsMedicinePrescriptionRecordVO> list = BeanCopierUtil.copy(dmsMedicinePrescriptionRecordService.selectDmsMedicinePrescriptionRecordList(dmsMedicinePrescriptionRecord), DmsMedicinePrescriptionRecordVO.class);
        ExcelUtil<DmsMedicinePrescriptionRecordVO> util = new ExcelUtil<DmsMedicinePrescriptionRecordVO>(DmsMedicinePrescriptionRecordVO.class);
        return util.exportExcel(list, "medicine_prescription_record");
    }

    /**
     * 获取成药处方详细信息
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取成药处方详细信息",
            notes = "根据成药处方id获取科室信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "dmsMedicinePrescriptionRecord.id", type = "Long")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(BeanCopierUtil.copy(dmsMedicinePrescriptionRecordService.selectDmsMedicinePrescriptionRecordById(id), DmsMedicinePrescriptionRecordVO.class));
    }

    /**
     * 新增成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:add')")
    @Log(title = "新增成药处方", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增成药处方信息", notes = "新增成药处方信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "POST")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsMedicinePrescriptionRecordVO对象", type = "DmsMedicinePrescriptionRecordVO")
    public AjaxResult add(@RequestBody DmsMedicinePrescriptionRecordVO dmsMedicinePrescriptionRecordVO) {
        //类型转换
        DmsMedicinePrescriptionRecord dmsMedicinePrescriptionRecord = BeanCopierUtil.copy(dmsMedicinePrescriptionRecordVO, DmsMedicinePrescriptionRecord.class);
        List<DmsMedicineItemRecord> list = BeanCopierUtil.copy(dmsMedicinePrescriptionRecord.getMedicineItemRecords(), DmsMedicineItemRecord.class);
        dmsMedicinePrescriptionRecord.setMedicineItemRecords(list);
        //存入缓存前的准备工作
        String key = DmsConstants.PRESCRIPTION_FOLDER + ":" + dmsMedicinePrescriptionRecord.getRegistrationId() + ":" + DmsConstants.CORRESPONDING_REGISTRATION;
        //如果处方状态为未开立，则将数据存入Redis,10分钟后过期  存储格式=(常量名:挂号ID:常量,集合对象)
        if (dmsMedicinePrescriptionRecord.getStatus() < 0) {
            redisTemplate.opsForList().rightPush(key, dmsMedicinePrescriptionRecord);
            redisTemplate.expire(key, 10, TimeUnit.MINUTES);
            return toAjax(1);
        } else {
            return toAjax(dmsMedicinePrescriptionRecordService.insertDmsMedicinePrescriptionRecord(dmsMedicinePrescriptionRecord));
        }
    }

    /**
     * 修改成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:edit')")
    @Log(title = "成药处方", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改成药处方信息", notes = "修改成药处方信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "PUT")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsMedicinePrescriptionRecordVO对象", type = "DmsMedicinePrescriptionRecordVO")
    public AjaxResult edit(@RequestBody DmsMedicinePrescriptionRecordVO dmsMedicinePrescriptionRecordVO) {
        return toAjax(dmsMedicinePrescriptionRecordService.updateDmsMedicinePrescriptionRecord(BeanCopierUtil.copy(dmsMedicinePrescriptionRecordVO, DmsMedicinePrescriptionRecord.class)));
    }

    /**
     * 修改成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:edits')")
    @Log(title = "成药处方", businessType = BusinessType.UPDATE)
    @PutMapping("/edits")
    @ApiOperation(value = "修改成药处方信息(发药)", notes = "修改成药处方信息(发药)", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "PUT")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    public AjaxResult edits(@RequestBody Map<String, Object> data) {
        List<Long> ids = (List<Long>) data.get("ids");
        //List去重
        List<Long> newids = ids.stream().distinct().collect(Collectors.toList());
        Integer status = (Integer) data.get("status");
        return toAjax(dmsMedicinePrescriptionRecordService.batchModificationOfPrescriptions(newids, status));
    }

    /**
     * 删除成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:remove')")
    @Log(title = "成药处方", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除成药处方信息", notes = "删除成药处方信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "DELETE")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "dmsMedicinePrescriptionRecord.id", type = "Long[]")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dmsMedicinePrescriptionRecordService.deleteDmsMedicinePrescriptionRecordByIds(ids));
    }

    /**
     * 删除redis缓存的成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:redisremove')")
    @Log(title = "成药处方", businessType = BusinessType.DELETE)
    @DeleteMapping("/del/{registrationId}/{names}")
    @ApiOperation(value = "删除成药处方信息", notes = "删除成药处方信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "DELETE")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "names", type = "String[]")
    public AjaxResult removeForRedis(@PathVariable Long registrationId, @PathVariable String[] names) {
        //获取缓存中的数据
        String key = DmsConstants.PRESCRIPTION_FOLDER + ":" + registrationId + ":" + DmsConstants.CORRESPONDING_REGISTRATION;
        List<DmsMedicinePrescriptionRecord> records = redisCache.getCacheList(key);
        List<String> nameList = Arrays.asList(names);
        for (DmsMedicinePrescriptionRecord mpr : records) {
            if (nameList.contains(mpr.getName())) {
                redisTemplate.opsForList().remove(key, 0, mpr);
            }
        }
        return toAjax(1);
    }

    /**
     * 开立成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:prescribe')")
    @Log(title = "开立成药处方", businessType = BusinessType.INSERT)
    @PostMapping("/prescribe/{registrationId}/{names}")
    @ApiOperation(value = "开立成药处方信息", notes = "开立成药处方信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "POST")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsMedicinePrescriptionRecordVO对象", type = "DmsMedicinePrescriptionRecordVO")
    public AjaxResult prescribe(@PathVariable Long registrationId, @PathVariable String[] names) {
        String key = DmsConstants.PRESCRIPTION_FOLDER + ":" + registrationId + ":" + DmsConstants.CORRESPONDING_REGISTRATION;
        List<DmsMedicinePrescriptionRecord> records = redisCache.getCacheList(key);
        List<String> nameList = Arrays.asList(names);
        for (DmsMedicinePrescriptionRecord mpr : records) {
            if (nameList.contains(mpr.getName())) {
                redisTemplate.opsForList().remove(key, 0, mpr);
                mpr.setStatus(1L);
                dmsMedicinePrescriptionRecordService.insertDmsMedicinePrescriptionRecord(mpr);
            }
        }
        return toAjax(1);
    }

    /**
     * 作废成药处方
     */
    @PreAuthorize("@ss.hasPermi('dms:medicine_prescription_record:voidPrescription')")
    @Log(title = "作废成药处方", businessType = BusinessType.INSERT)
    @PostMapping("/voidPrescription/{registrationId}/{names}")
    @ApiOperation(value = "作废成药处方信息", notes = "作废成药处方信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "POST")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsMedicinePrescriptionRecordVO对象", type = "DmsMedicinePrescriptionRecordVO")
    public AjaxResult voidPrescription(@PathVariable Long registrationId, @PathVariable String[] names) {
        String key = DmsConstants.PRESCRIPTION_FOLDER + ":" + registrationId + ":" + DmsConstants.CORRESPONDING_REGISTRATION;
        List<DmsMedicinePrescriptionRecord> records = redisCache.getCacheList(key);
        List<String> nameList = Arrays.asList(names);
        for (DmsMedicinePrescriptionRecord mpr : records) {
            if (nameList.contains(mpr.getName())) {
                redisTemplate.opsForList().remove(key, 0, mpr);
                mpr.setStatus(0L);
                dmsMedicinePrescriptionRecordService.insertDmsMedicinePrescriptionRecord(mpr);
            }
        }
        return toAjax(1);
    }

}
